import { useState, useRef, useEffect } from 'react';
import { message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import './index.scss';

/**
 * 上传组件
 */
export default ({ value, onChange, style, attrs, tip, size, type }) => {
    /**
     * 图片路径
     */
    const [fileName, setFileName] = useState('');
    /**
     * 上传组件引用
     */
    const upload = useRef();
    /**
     * 处理文件
     * @param {*} file 要处理的文件
     */
    const handleFile = file => {
        console.log(file);
        const { size: s, type: t } = file;
        if (typeof size === 'number' && s > size) {
            return message.warning('上传的文件过大');
        }
        if (type && !type.test(t)) {
            return message.warning('上传的文件格式不正确');
        }
        const path = (window.URL || window.webkitURL || window).createObjectURL(file);
        setFileName(path);
        onChange(file);
    }

    useEffect(() => {
        if (typeof value === 'string') {
            setFileName(process.env.REACT_APP_BASE_URL + value);
            onChange(undefined);
        }
    }, [value]);


    return <div className="form-upload" style={style}>
        <img style={{ display: !fileName && 'none' }} src={fileName} width={100} height={100} onClick={() => upload.current.click()} />
        <label style={{ display: !!fileName && 'none' }}>
            <PlusOutlined />
            <input {...attrs} type="file" ref={upload} accept="image/*" style={{ display: 'none' }} onChange={e => handleFile(e.target.files[0])} />
        </label>
        <font color="red">{tip}</font>
    </div>
}